package com.baidu.mpks.common;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.AbstractHttpMessage;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class HttpClientTemplate {

    private HttpClient httpClient;
    private int maxLength = 1024;
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientTemplate.class);

    public HttpClientTemplate() {
    }

    private String convertUrlWithParam(String url, Map<String, String> getParam) {
        if (getParam != null && !getParam.isEmpty()) {
            List<NameValuePair> nvps = new ArrayList();
            Iterator var4 = getParam.entrySet().iterator();

            while(var4.hasNext()) {
                Map.Entry<String, String> me = (Map.Entry)var4.next();
                nvps.add(new BasicNameValuePair((String)me.getKey(), (String)me.getValue()));
            }

            String param = URLEncodedUtils.format(nvps, "utf-8");
            url = url + (url.contains("?") ? param : "?" + param);
        }

        return url;
    }

    private String processResponse(HttpResponse response, String charsetName) throws IOException {
        int code = response.getStatusLine().getStatusCode();
        if (code / 100 != 2) {
            throw new IOException(" status code " + code);
        } else {
            return EntityUtils.toString(response.getEntity(), "utf-8");
        }
    }

    private void addHeader(AbstractHttpMessage httpMessage) {
        httpMessage.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        httpMessage.setHeader("Accept-Language", "zh-CN,zh");
        httpMessage.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36");
    }

    public String executeGet(String url, Map<String, String> getParam) throws IOException {
        return this.executeGet(url, getParam, (Integer)null);
    }

    public String executeGet(String url, Map<String, String> getParam, Integer timeOut) throws IOException {
        HttpGet httpGet = new HttpGet(this.convertUrlWithParam(url, getParam));
        if (timeOut != null) {
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeOut).setConnectTimeout(timeOut).build();
            httpGet.setConfig(requestConfig);
        }

        String var6;
        try {
            HttpResponse response = this.httpClient.execute(httpGet);
            var6 = this.processResponse(response, "utf-8");
        } finally {
            httpGet.releaseConnection();
        }

        return var6;
    }

    public String executeGet(String url, Map<String, String> getParam, Integer timeOut, Map<String, String> header) throws IOException {
        HttpGet httpGet = new HttpGet(this.convertUrlWithParam(url, getParam));
        if (header != null) {
            header.forEach(httpGet::addHeader);
        }

        if (timeOut != null) {
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeOut).setConnectTimeout(timeOut).build();
            httpGet.setConfig(requestConfig);
        }

        String var7;
        try {
            HttpResponse response = this.httpClient.execute(httpGet);
            var7 = this.processResponse(response, "utf-8");
        } finally {
            httpGet.releaseConnection();
        }

        return var7;
    }

    public String executePostForm(String url, Map<String, String> getParam, Map<String, String> postParam) throws IOException {
        HttpPost httpPost = new HttpPost(this.convertUrlWithParam(url, getParam));
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");

        String var12;
        try {
            if (postParam != null && !postParam.isEmpty()) {
                List<NameValuePair> nvps = new ArrayList();
                Iterator var6 = postParam.entrySet().iterator();

                while(var6.hasNext()) {
                    Map.Entry<String, String> me = (Map.Entry)var6.next();
                    nvps.add(new BasicNameValuePair((String)me.getKey(), (String)me.getValue()));
                }

                httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            }

            HttpResponse response = this.httpClient.execute(httpPost);
            var12 = this.processResponse(response, "utf-8");
        } finally {
            httpPost.releaseConnection();
        }

        return var12;
    }

    public String executePostData(String url, Map<String, String> getParam, String data) throws IOException {
        HttpPost httpPost = new HttpPost(this.convertUrlWithParam(url, getParam));
        httpPost.setHeader("Content-type", "application/json; charset=utf-8");

        String var6;
        try {
            if (data != null && !data.isEmpty()) {
                httpPost.setEntity(new StringEntity(data, Charset.forName("utf-8")));
            }

            LOGGER.info("post url-->{}", url);
            HttpResponse response = this.httpClient.execute(httpPost);
            var6 = this.processResponse(response, "utf-8");
        } finally {
            httpPost.releaseConnection();
        }

        return var6;
    }

    public String executeDeleteData(String url, String data) throws IOException {
        HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
        httpDelete.addHeader("Content-type", "application/json; charset=utf-8");

        String var5;
        try {
            if (data != null && !data.isEmpty()) {
                httpDelete.setEntity(new StringEntity(data, ContentType.APPLICATION_JSON));
            }

            HttpResponse response = this.httpClient.execute(httpDelete);
            var5 = this.processResponse(response, "utf-8");
        } finally {
            httpDelete.releaseConnection();
        }

        return var5;
    }

    public String executePostData(String url, Map<String, String> getParam, String data, Map<String, String> headerParam) throws IOException {
        HttpPost httpPost = new HttpPost(this.convertUrlWithParam(url, getParam));
        httpPost.addHeader("Content-type", "application/json; charset=utf-8");
        if (headerParam != null && !headerParam.isEmpty()) {
            Iterator var6 = headerParam.entrySet().iterator();

            while(var6.hasNext()) {
                Map.Entry<String, String> entry = (Map.Entry)var6.next();
                httpPost.addHeader((String)entry.getKey(), (String)entry.getValue());
            }
        }

        String var12;
        try {
            if (data != null && !data.isEmpty()) {
                httpPost.setEntity(new StringEntity(data, Charset.forName("utf-8")));
            }

            HttpResponse response = this.httpClient.execute(httpPost);
            var12 = this.processResponse(response, "utf-8");
        } finally {
            httpPost.releaseConnection();
        }

        return var12;
    }

    public String executePostDataWithHeaders(String url, Map<String, String> getParam, String json, Map<String, String> header, ResponseHandler<String> responseHandler) throws IOException {
        HttpPost httpPost = new HttpPost(this.convertUrlWithParam(url, getParam));
        header.forEach(httpPost::addHeader);

        String var7;
        try {
            if (json != null && !json.isEmpty()) {
                httpPost.setEntity(new StringEntity(json, Charset.forName("utf-8")));
            }

            var7 = (String)this.httpClient.execute(httpPost, responseHandler);
        } finally {
            httpPost.releaseConnection();
        }

        return var7;
    }

    public HttpClient getHttpClient() {
        return this.httpClient;
    }

    public void setHttpClient(HttpClient httpClient) {
        this.httpClient = httpClient;
    }

    public int getMaxLength() {
        return this.maxLength;
    }

    public void setMaxLength(int maxLength) {
        this.maxLength = maxLength;
    }
}
